import React, {
	PureComponent
} from 'react'
import { connect } from 'dva'
import { Form, Input, Button, Transfer } from 'antd'
import Tabs from '@/components/Tabs/Tabs'
import Select from '@/components/Select'
import Grid from '@/components/Grid'
import Dialog, { withRef } from '@/components/Dialog'
import settings, { getPagination } from '@/settings'
import { mapping, isAdmin } from '@/utils'
import { $request, $http } from '@/utils/request'
import Authorized, { checkRouteAuth } from '@/components/Authorized'

// const ModelForm = Form.create()(props => {
// 	return (
// 	)
// })

@Form.create()
@connect(({ app: { user={} }, user: { data, units, roles, roleIds } }) => ({ user, data, units, roles, roleIds }))
@withRef
class ModelForm extends React.Component {
	state = {
		confirmDirty: false,
		// targetKeys: [],
    	selectedKeys: []
	};
	formLayout = {
		// labelAlign: 'left',
		// labelCol: {
		// 	span: 5
		// },
		// wrapperCol: {
		// 	span: 19
		// },
	};
	componentDidMount() {
		const {
			id,
			user,
			dispatch
		} = this.props;

		const {
			authorities = []
		} = user
		
		if (isAdmin(user) || checkRouteAuth(authorities)('ORG_VIEW')) {
			dispatch({
				type: 'user/fetchUnits'
			});
		}
		if (isAdmin(user) || checkRouteAuth(authorities)('ROLE_VIEW')) {
			dispatch({
				type: 'user/fetchRoles'
			});
		}

		if (id) {
			dispatch({
				type: 'user/fetchOne',
				payload: {
					id
				}
			});
		}
	};
	handleSubmit = (_, callback) => {
		const {
			roleIds,
			form
		} = this.props

		form.validateFields((err, values) => {
			if (!err) {
				callback({
					...values,
					// roleIds: this.state.targetKeys
					roleIds
				})
			}
		})
	};
	// filterOption = (inputValue, option) => option.description.indexOf(inputValue) > -1;
	handleChange = targetKeys => {
	    const {
	    	dispatch
	    } = this.props
	    // this.setState({ targetKeys });
	    dispatch({
	    	type: 'user/updateState',
	    	payload: {
	    		roleIds: targetKeys
	    	}
	    })
	};
	handleConfirmBlur = e => {
		const value = e.target.value;
		this.setState({
			confirmDirty: this.state.confirmDirty || !!value
		});
	};
	compareToFirstPassword = (rule, value, callback) => {
		const form = this.props.form;
		if (value && value !== form.getFieldValue('password')) {
			callback('两次输入的密码不一致');
		} else {
			callback();
		}
	};
	validateToNextPassword = (rule, value, callback) => {
		const { form } = this.props;
		if (value && this.state.confirmDirty) {
			form.validateFields(['confirmPassword'], {
				force: true
			});
		}
		callback();
	};
	render() {
		// const {
		// 	targetKeys
		// } = this.state
		const {
			id,
			roleIds: targetKeys,
			user,
			data = {},
			roles = [],
			units = [],
			form: {
				getFieldDecorator
			}
		} = this.props

		const {
			authorities = []
		} = user

		const options = units.map(_ => <Select.Option key={_.id} value={_.id}>{_.name}</Select.Option>)

		return (
			<Tabs defaultActiveKey="1">
				<Tabs.TabPane tab="用户信息" key="1">
					<Form layout="vertical">
					{/*<Form>*/}
			          <Form.Item label="用户名" {...this.formLayout}>
			            {getFieldDecorator('name', {
			            	validateFirst: true,
							rules: [{
								required: true,
								message: '请输入用户名'
							}, {
								validator: (rule, value, callback) => {
									$http.post('valid/username', {
										data: {
											id,
											value
										},
										type: true,
										requestType: 'form'
									}).then(data => {
										data.valid ? callback() : callback("用户名已存在")
									})
								}
							}],
				            initialValue: data.name,
			            })(<Input placeholder="请输入" />)}
			          </Form.Item>
			          { !id && (
			          	<React.Fragment>
				          <Form.Item label="密码" {...this.formLayout}>
				            {getFieldDecorator('password', {
								rules: [{
									required: true,
									message: '请输入密码'
								}, {
									validator: this.validateToNextPassword
								}]
				            })(<Input.Password placeholder="请输入" />)}
				          </Form.Item>
				          <Form.Item label="确认密码" {...this.formLayout}>
				            {getFieldDecorator('confirmPassword', {
								rules: [{
									required: true,
									message: '请输入密码'
								}, {
									validator: this.compareToFirstPassword
								}]
				            })(<Input.Password placeholder="请输入" onBlur={this.handleConfirmBlur} />)}
				          </Form.Item>
				        </React.Fragment>
			          	)
			          }
			          <Form.Item label="真实姓名" {...this.formLayout}>
			            {getFieldDecorator('realname', {
			              rules: [{ required: true, message: '请输入真实姓名' }],
			              initialValue: data.realname,
			            })(<Input placeholder="请输入" />)}
			          </Form.Item>
			          {isAdmin(user) || checkRouteAuth(authorities)('ORG_VIEW') ? <Form.Item label="选择部门" {...this.formLayout}>
			            {getFieldDecorator('orgId', {
			              rules: [{ required: true, message: '请选择选择部门' }],
			              initialValue: data.orgId,
			            })(
			              <Select>
			                {options}
			              </Select>
			            )}
			          </Form.Item> : null}
			          <Form.Item label="联系电话" {...this.formLayout}>
			            {getFieldDecorator('phone', {
							rules: [{
								pattern: /^\d{11}$/,
								message: '请输入十一位手机号码'
							}],
			              	initialValue: data.phone,
			            })(<Input placeholder="请输入" />)}
			          </Form.Item>
			          <Form.Item label="email" {...this.formLayout}>
			            {getFieldDecorator('email', {
							rules: [{
				                type: 'email',
				                message: '请输入正确的电子邮箱',
				            }],
			              	initialValue: data.email,
			            })(<Input placeholder="请输入" />)}
			          </Form.Item>
			        </Form>
				</Tabs.TabPane>
				<Tabs.TabPane tab="所属角色" key="2">
					<Transfer
						rowKey={record => record.id}
				        dataSource={roles}
				        listStyle={{
				          width: 210,
				          height: 300,
				        }}
				        // showSearch
				        // filterOption={this.filterOption}
				        targetKeys={targetKeys}
				        onChange={this.handleChange}
				        render={item => item.name}
				    />
				</Tabs.TabPane>
			</Tabs>
		)
	}
}

// @Form.create()
// class SearchForm extends React.Component {
// 	state = {
// 		data: {}
// 	};
// 	render() {
// 		const { data } = this.state
// 		const {
// 			form: {
// 				getFieldDecorator
// 			}
// 		} = this.props
// 		return (
// 			<Form onSubmit={this.handleSubmit} layout="vertical">
// 	          <Form.Item label="任务名称" {...this.formLayout}>
// 	            {getFieldDecorator('title', {
// 	              rules: [{ required: true, message: '请输入任务名称' }],
// 	              initialValue: data.title,
// 	            })(<Input placeholder="请输入" />)}
// 	          </Form.Item>
// 	          <Form.Item label="开始时间" {...this.formLayout}>
// 	            {getFieldDecorator('date', {
// 	              rules: [{ required: true, message: '请选择开始时间' }],
// 	              initialValue: data.date ? moment(data.date) : null,
// 	            })(
// 	              <DatePicker
// 	                showTime
// 	                placeholder="请选择"
// 	                format="YYYY-MM-DD HH:mm:ss"
// 	                style={{ width: '100%' }}
// 	              />
// 	            )}
// 	          </Form.Item>
// 	          <Form.Item label="任务负责人" {...this.formLayout}>
// 	            {getFieldDecorator('owner', {
// 	              rules: [{ required: true, message: '请选择任务负责人' }],
// 	              initialValue: data.owner,
// 	            })(
// 	              <Select placeholder="请选择">
// 	                <Select.Option value="付晓晓">付晓晓</Select.Option>
// 	                <Select.Option value="周毛毛">周毛毛</Select.Option>
// 	              </Select>
// 	            )}
// 	          </Form.Item>
// 	          <Form.Item {...this.formLayout} label="产品描述">
// 	            {getFieldDecorator('desc', {
// 	              rules: [{ message: '请输入至少五个字符的产品描述！', min: 5 }],
// 	              initialValue: data.desc,
// 	            })(<Input.TextArea rows={4} placeholder="请输入至少五个字符" />)}
// 	          </Form.Item>
// 	        </Form>
// 		)
// 	}
// }

@connect(({
	app: {
		user = {}
	},
	user: {
		list = {},
		params
	},
	loading
}) => ({
	user,
	list,
	params,
	loading: loading.effects['user/fetchAll'],
}))
@Form.create()
class UserPage extends PureComponent {
	state = {
		selectedRows: []
	};
	columns = [{
		title: '用户名',
		dataIndex: 'name',
		width: 200
	}, {
		title: '真实姓名',
		dataIndex: 'realname',
		width: 120,
		align: 'center'
	}, {
		title: '邮箱',
		dataIndex: 'mail',
		width: 200
	}, {
		title: '手机号码',
		dataIndex: 'phone',
		width: 150
	}, {
		title: '所属部门',
		dataIndex: 'orgId',
		width: 200,
		render: (v, record, index) => {
			const {
				list: {
					fields = {}
				}
			} = this.props
			const {
				orgs = {}
			} = fields
			return mapping(v, orgs)
		}
	}, {
		title: '当前状态',
		dataIndex: 'enabled',
		width: 100,
		align: 'center',
		render: (v, record, index) => {
			const types = [{
				name: '已启用',
				value: true
			}, {
				name: '已停用',
				value: false
			}]
			return mapping(v, types)
		}
	}, {
		title: '创建时间',
		dataIndex: 'crtime',
		width: 200,
		align: 'center'
	}];
	componentDidMount() {
		const {
			dispatch
		} = this.props;
		dispatch({
			type: 'user/fetchAll',
		});
	};
	handleSelectRows = rows => {
		this.setState({
			selectedRows: rows,
		});
	};
	handleAdd = e => {
		const {
			user,
			dispatch
		} = this.props;
		const {
			authorities = []
		} = user
		dispatch({
			type: 'user/reset'
		});
		Dialog.open({
			title: '新建用户',
			fixed: true,
			component: ModelForm,
			url: 'user/add',
			onOk: data => {
				this.handleReload()
			},
			// onOk: ({ reject, resolve }, data) => {
			// 	$request.post('user/add', {
			// 		data
			// 	}).then(data => {
			// 		resolve()
			// 		this.handleReload()
			// 	})
			// },
			connect: isAdmin(user) || checkRouteAuth(authorities)('ORG_VIEW') ? ({ loading }) => ({ loading: loading.effects['user/fetchUnits'] && loading.effects['user/fetchRoles'] }) : null
		})
	};
	handleEdit = e => {
		const { selectedRows } = this.state;
		const { id } = selectedRows[0];
		const {
			user,
			dispatch
		} = this.props;
		const {
			authorities = []
		} = user
		dispatch({
			type: 'user/reset'
		});
		Dialog.open({
			title: '修改用户',
			fixed: true,
			url: 'user/update',
			data: {
				id
			},
			options: {
				type: 'put'
			},
			onOk: data => {
				this.handleReload()
			},
			// onOk: (close, data) => {
			// 	$request.put('user/update', {
			// 		data: {
			// 			...data,
			// 			id
			// 		}
			// 	}).then(data => {
			// 		close()
			// 		this.handleReload()
			// 	})
			// },
			component: props => (<ModelForm {...props} id={id} />),
			connect: ({ loading }) => ({ loading: (isAdmin(user) || checkRouteAuth(authorities)('ORG_VIEW') ? loading.effects['user/fetchUnits'] : true) && (isAdmin(user) || checkRouteAuth(authorities)('ROLE_VIEW') ? loading.effects['user/fetchRoles'] : true) && loading.effects['user/fetchOne'] })
		})
	};
	handleRemove = e => {
		const { selectedRows } = this.state;
		Dialog.confirm({
			title: '确认提示',
			content: '确定要删除已选择的用户？',
			onOk: () => {
				$request.put('user/delete', {
					data: {
						ids: selectedRows.map(_ => _.id)
					}
				}).then(data => {
					this.handleReload()
				})
			}
		})
	};
	handleGridChange = (oldPagination, sorter) => {
		const { params, dispatch } = this.props;
		
		const pagination = getPagination(oldPagination)
		const payload = {
			...params,
			...pagination
		}

		if (sorter.field) {
			payload.sorter = sorter.field
			payload.order = sorter.order
		}

		dispatch({
			type: 'user/fetchAll',
			payload,
		})
	};
	handleReload = () => {
		const { params, dispatch } = this.props;
		dispatch({
			type: 'user/fetchAll',
			payload: params
		})
	};
	handleSearch = (value, e) => {
		e.preventDefault();
		const { params, dispatch } = this.props;
		const pagination = getPagination({
			pageNumber: 1
		})
		dispatch({
			type: 'user/fetchAll',
			payload: {
				...params,
				...pagination,
				name: value
			}
		})
	};
	// showSearchPanel = e => {
	// 	Dialog.drawer({
	// 		title: '高级查询',
	// 		component: SearchForm
	// 	})
	// }
	render() {
		const { selectedRows } = this.state;
		const {
			user: {
				authorities = []
			},
			params,
			// form: {
			// 	getFieldDecorator
			// },
			loading,
			list: {
				data,
				total
			}
		} = this.props

		const pageNumber = params[settings.pageNumber]
		return (
			<div className="x-wrap">
				{/*<div className="x-header">
					<div className="x-title"><span className="title-text">用户管理</span></div>
				</div>*/}
				<div className="x-panel">
					<div className="x-toolbar">
						<div className="fl">
							<Authorized authorities={authorities} authority="USER_ADD"><Button type="primary" onClick={this.handleAdd}>新建</Button></Authorized>
							<Authorized authorities={authorities} authority="USER_EDIT"><Button onClick={this.handleEdit} disabled={selectedRows.length !== 1}>编辑</Button></Authorized>
							<Authorized authorities={authorities} authority="USER_DEL"><Button type="danger" disabled={selectedRows.length === 0} onClick={this.handleRemove}>删除</Button></Authorized>
						</div>
						<div className="fr x-query">
							<Form layout="inline">
								<Input.Search placeholder="请输入要查询的关键词" onSearch={this.handleSearch} />
								{/*<Button onClick={this.showSearchPanel}>高级查询</Button>*/}
							</Form>
						</div>
					</div>
					<div className="x-fixed">
						<Grid 
						selectedRows={selectedRows} 
						onSelectRow={this.handleSelectRows} 
						columns={this.columns} 
						data={data}
						loading={loading}
						pagination={{
							pageNumber,
							total
						}}
						onReload={this.handleReload}
						onChange={this.handleGridChange} />
					</div>
				</div>
			</div>
		)
	}
}

export default UserPage